use std::{error::Error, fs};

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let content = fs::read_to_string(config.filename)?;
    let result = search(&config.query, &content);
    println!("result is {:?}", result);
    Ok(())
}
pub struct Config {
    query: String,
    filename: String,
}

impl Config {
    pub fn new(args: &[String]) -> Config {
        let query = args[1].clone();
        let filename = args[2].clone();
        Config { query, filename }
    }
}

pub fn parse_config(args: &[String]) -> Result<Config, &'static str> {
    // 处理异常
    if args.len() < 3 {
        return Err("not enough arguments");
    }
    Ok(Config::new(args))
}

pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    let mut result = Vec::new();
    for line in content.lines() {
        if line.contains(query) {
            result.push(line)
        }
    }
    result
}

#[cfg(test)]
mod test {
    // 引入需要测试的模块
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let content = "\
Rust:
safe, fase, productive.
Pick three
";
        assert_eq!(vec!["safe, fase, productive."], search(query, content))
    }
}
